package de.sendorian.app.forumArchive;


import java.io.File;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.hamcrest.Matcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import de.sendorian.util.io.RecursiveFileListIterator;
import de.sendorian.util.matcher.FileTypeMatchers;

@Component
public class Cleaner {
    private static final Logger LOG = Logger.getLogger(Cleaner.class);

    public static void main(String[] args) {
		new Cleaner().cleanup();
	}
    
	private @Value("#{props.download_dir}") String downloadDir;

	public void cleanup() {
		File fDownloadDir = new File(downloadDir);
		if (!fDownloadDir.exists()) {
			LOG.info("Download dir not found. Cancelling cleanup. ("+downloadDir+")");
			return;
		}
		
		Matcher<String> filesMatcher = FileTypeMatchers.ignoredFiles();
		Iterator<File> it = new RecursiveFileListIterator(fDownloadDir);

		while(it.hasNext()) {
			File file = it.next();
			if (filesMatcher.matches(file.getName())) {
				file.delete();
            }
		}
		LOG.info("Finished cleanup.");
	}

	public void setDownloadDir(String downloadDir) {
		this.downloadDir = downloadDir;
	}

}
